package com.tac.common.Exception;

import com.tac.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestControllerAdvice(annotations = {RestController.class})
@Slf4j
@CrossOrigin
public class GlobalExcetion {

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(TokenException.class)
    public Result<String> exception(TokenException ex){
       return Result.error(ex.getMessage(),401);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(CostomException.class)
    public Result<String> exception(CostomException ex){
        return Result.error(ex.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> exception(MethodArgumentNotValidException ex){
        //日志记录错误信息
        log.error(Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage());
        //将错误信息返回给前台
        return Result.error(Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage(),400);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<String> exception(Exception ex){
        log.info("异常原因：{}",ex.getMessage());
       return Result.error(ex.getMessage());
    }
}
